package day12.handler.simpleChannelHandler.response;

import day09.handler.simpleChannelHandler.LoginRequestHandler;
import day12.packet.response.LoginResponsePacket;
import day12.util.session.Session;
import day12.util.session.SessionUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;

/**
 * @author chenshijie
 * @date 2023/12/26 13:31
 */
@ChannelHandler.Sharable
public class LoginResponseHandler extends SimpleChannelInboundHandler<LoginResponsePacket> {

    public static final LoginResponseHandler INSTANCE = new LoginResponseHandler();

    protected LoginResponseHandler() {

    }

//    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//
//        // 创建登录对象
//        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
////        loginRequestPacket.setUserId(123);
//        loginRequestPacket.setUsername("yu");
//        loginRequestPacket.setPassword("password");
//
//        // 编码
////        ByteBuf buffer = PacketCodeC.INSTANCE.encode(ctx.alloc(), loginRequestPacket);
//
//        // 写数据
//        ctx.channel().writeAndFlush(loginRequestPacket);
//    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginResponsePacket loginResponsePacket) throws Exception {
        loginResponse(ctx, loginResponsePacket);
    }

    private static void loginResponse(ChannelHandlerContext ctx, LoginResponsePacket loginResponsePacket) {

        if (loginResponsePacket.isSuccess()) {
            System.out.println(new Date() + ": 客户端登录成功，用户id为【" + loginResponsePacket.getUserId() + "】");

            SessionUtil.bindSession(new Session(loginResponsePacket.getUserId(), loginResponsePacket.getUsername()), ctx.channel());

        } else {
            System.out.println(new Date() + ": 客户端登录失败：" + loginResponsePacket.getMessage());
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端连接被关闭");
    }
}
